package cc.linker.steplink.crm.mq.content;

import cc.linker.steplink.crm.commons.Constants;
import cc.linker.steplink.crm.commons.RandomCodeGenerator;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.dao.*;
import cc.linker.steplink.crm.domain.*;
import cc.linker.steplink.crm.merchanth5.service.SurvivalPushService;
import cc.linker.steplink.crm.merchanth5.service.WxShareService;
import cc.linker.steplink.crm.service.ISysConfig;
import cc.linker.steplink.crm.service.RobotSurveyService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 接收内容库mq消息
 * @Author: wuyue
 * @Date: 2019/8/30 13:30
 * @Version: v1.8.3
 */
@Slf4j
@Component
public class ActionMqReceiver {

    private static final Integer SUBSCRIBE_DEFAULT = 2;
    private static final String MARKET_ROBOT_SWITCH = "marketRobotSwitch";
    private static final String GET_WEIXIN_USER_INFO = "getWeixinUserInfo";
    private static final String ARTICLE_BEHAVIOR = "article_behavior_";

    @Autowired
    private PersonalDao personalDao;
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private HttpService httpService;
    @Autowired
    private SyncContentDao syncContentDao;
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private CustomerInfoDao customerInfoDao;
    @Autowired
    private CustomerInfoWxDao customerInfoWxDao;
    @Autowired
    private RobotSurveyService robotSurveyService;
    @Autowired
    private ISysConfig sysConfig;
    @Autowired
    private WxShareService wxShareService;
    @Autowired
    private SurvivalPushService survivalPushService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ScoreActDao scoreActDao;

    /**
     * @Description: 拉取内容库mq行为数据
     * @Param: ContentAction中除了customerId和actionContentId
     * @Return: void
     * @Author: wuyue
     * @Date: 2019/8/30 17:19
     * @Version: v1.8.3
     */
    /**
     * @Modify: wuyue
     * @Date: 2019/9/3 16:32
     * @Description:增加阅读次数
     * @Version: v1.8.3
     */
    public void direct(String msg) {
        try {


            LOGGER.info("从mq接收内容库行为数据：" + msg);
            ContentAction contentAction = JSON.parseObject(msg, ContentAction.class);
//            ContentAction contentActionTmp = JSON.parseObject(msg, ContentAction.class);

            String openid = contentAction.getOpenId();
            String token = contentAction.getToken();

            if (StringUtils.isEmpty(openid) || StringUtils.isEmpty(token)) {
                LOGGER.error("同步失败，用户信息缺失");
                return;
            }
            String orgId = personalDao.getOrgIdByToken(token, "");
            if (StringUtils.isEmpty(orgId)) {
                LOGGER.warn("未绑定公众号，不同步");
                return;
            }

            // 根据openid+orgId找customerId
            String customerId = personalDao.getCustomerIdByOpenIdAndOrgId(openid, orgId);
            if (StringUtils.isEmpty(customerId)) {
                // 由于未关注逻辑的存在，每一个用户都要根据token+openid和token+globalOpenid两次判断，才能确保用户机构下唯一
                customerId = personalDao.getCustomerIdByWxGlobalOpenIdAndOrgId(openid, orgId);
            }

            // 关注状态,赋一个自定义初始值
            Integer subscribe = SUBSCRIBE_DEFAULT;
            // 组装请求矩阵的参数
            Map<String, Object> params = new HashMap<>(4);
            params.put("action", GET_WEIXIN_USER_INFO);
            params.put("openid", openid);
            params.put("token", token);
            if (StringUtils.isEmpty(customerId)) {
                LOGGER.info("系统中找不到对应用户，新建用户");
                // 矩阵返回结果
                String result;
                try {
                    result = httpService.doPost(systemProperties.getWxpushurl(), JSON.toJSONString(params));
                } catch (Exception e) {
                    LOGGER.error("矩阵调用异常");
                    return;
                }
                WxUserInfoDto wxUserInfoDto = JSON.parseObject(result, WxUserInfoDto.class);
                if ("200".equals(wxUserInfoDto.getErrcode())) {
                    WxUserInfo wxUserInfo = wxUserInfoDto.getData();
                    subscribe = wxUserInfo.getSubscribe();
                    //客户信息
                    Customer customer = new Customer();
                    customer.setCustomerName(wxUserInfo.getNickname());
                    customer.setCustomerAvatar(wxUserInfo.getHeadimgurl());
                    customer.setCustomerSourceChannel((byte) 2);
                    customer.setWxGlobalOpenid("");
                    customer.setWxToken(token);
                    customer.setWxOpenid(openid);
                    customer.setCreateUser("内容库");
                    customer.setOrgId(contentAction.getOrganizationNum());
                    //客户拓展信息
                    CustomerInfo customerInfo = new CustomerInfo();
                    String area = "";
                    if (!StringUtils.isEmpty(wxUserInfo.getCountry()) && !"null".equals(wxUserInfo.getCountry())) {
                        area += wxUserInfo.getCountry();
                    }
                    area += "@";
                    if (!StringUtils.isEmpty(wxUserInfo.getProvince()) && !"null".equals(wxUserInfo.getProvince())) {
                        area += wxUserInfo.getProvince();
                    }
                    area += "@";
                    if (!StringUtils.isEmpty(wxUserInfo.getCity()) && !"null".equals(wxUserInfo.getCity())) {
                        area += wxUserInfo.getCity();
                    }
                    customerInfo.setCustomerArea(area);
                    //客户微信信息
                    CustomerInfoWx customerInfoWx = new CustomerInfoWx();
                    if (wxUserInfo.getSex() != null) {
                        customerInfoWx.setWxGender(wxUserInfo.getSex().byteValue());
                    }
                    customerInfoWx.setWxGlobalOpenid(wxUserInfo.getOpenid());
                    customerInfoWx.setWxAddress(area);
                    customerInfoWx.setWxName(wxUserInfo.getNickname());
                    customerInfoWx.setWxRemark(wxUserInfo.getRemark());
                    customerInfoWx.setWxToken(token);
                    customerInfoWx.setWxOpenid(openid);
                    customerInfoWx.setWxGlobalOpenid("");
                    customerInfoWx.setWxAvatar(wxUserInfo.getHeadimgurl());

                    customerId = RandomCodeGenerator.getCustomerId(Constants.CUSTOMER_CODE_SOURCE_CONTENT);
                    customer.setCustomerId(customerId);

                    customerInfo.setCustomerId(customer.getCustomerId());
                    customerInfo.setCustomerInfoId(UUID.randomUUID().toString());
                    customerInfoWx.setCustomerId(customer.getCustomerId());
                    customerDao.insertCustomer(customer);
                    customerInfoDao.insertSelective(customerInfo);
                    customerInfoWxDao.insertSelective(customerInfoWx);

                } else {
                    LOGGER.error("矩阵调用失败" + JSON.toJSONString(wxUserInfoDto));
                    return;
                }
            }
            // 记录行为
            contentAction.setCustomerId(customerId);

            //阅读文章促活
            if (null != contentAction.getUserOperate() && contentAction.getUserOperate() == 0) {
                String artId = contentAction.getNewsId();
                Map<String, Object> newsParams = new HashMap<>();
                newsParams.put("action", "readNews");
                newsParams.put("customerId", customerId);
                newsParams.put("openId", openid);
                newsParams.put("token", token);
                newsParams.put("orgId", orgId);
                newsParams.put("lastInteractionTime", null);
                newsParams.put("articleId", artId);
                wxShareService.addcactivelog(newsParams);
                String logId = newsParams.get("logId").toString();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String actionTime = sdf.format(new Date());
                survivalPushService.setPushSurvival(customerId, logId, "readNews", actionTime, null, orgId, artId,null);
            }

//        contentAction.setActionContentId(UUID.randomUUID().toString());
            if (contentAction.getReadTimeSum() == null) {
                contentAction.setReadTimeSum("0");
            }
            if (StringUtils.isEmpty(contentAction.getId())) {
                // 没带主键
                return;
            }


            Integer isExit = 0;
            if(contentAction.getUserOperate()==5 || contentAction.getUserOperate()==6 || contentAction.getUserOperate()==0) {
                if (contentAction.getUserOperate() == 5 || contentAction.getUserOperate() == 6) {
                    isExit = this.syncContentDao.isExitCustomerAction(contentAction);
                }
                String parentOrgId = "";
                String parentCustomerId = "";
                //如果是阅读 并且 阅读人和父级人不一致
                boolean isShare = false;
                if (!StringUtils.isEmpty(contentAction.getParentOpenId()) && !StringUtils.isEmpty(contentAction.getParentToken()) && contentAction.getUserOperate() == 0 && !contentAction.getParentOpenId().equals(contentAction.getOpenId())) {
                    parentOrgId = personalDao.getOrgIdByToken(contentAction.getParentToken(), "");
                    if (!StringUtils.isEmpty(parentOrgId)) {
                        // 根据openid+orgId找customerId
                        parentCustomerId = personalDao.getCustomerIdByOpenIdAndOrgId(contentAction.getParentOpenId(), parentOrgId);
                        //如果用户未找到，用globalopenid去找用户
                        if (StringUtils.isEmpty(parentCustomerId)) {
                            parentCustomerId = personalDao.getCustomerIdByWxGlobalOpenIdAndOrgId(contentAction.getParentOpenId(), parentOrgId);
                        }
                        if (!StringUtils.isEmpty(parentCustomerId)) {
//                            contentActionTmp.setId(UUID.randomUUID().toString());
//                            contentActionTmp.setCustomerId(parentCustomerId);
//                            contentActionTmp.setUserOperate(8);
//                            contentActionTmp.setOpenId(contentAction.getParentOpenId());
//                            contentActionTmp.setToken(contentAction.getParentToken());
//                            String remark = contentActionTmp.getUserOperateDescribe().replace("打开", "分享");
//                            contentActionTmp.setUserOperateDescribe(remark);
//                            if (contentActionTmp.getReadTimeSum() == null) {
//                                contentActionTmp.setReadTimeSum("0");
//                            }
//                            isExit = this.syncContentDao.isExitCustomerAction(contentActionTmp);
                            Boolean isOpened = stringRedisTemplate.opsForSet().isMember("contentAction", contentAction.getNewsId() + parentCustomerId + contentAction.getCustomerId());
                            if(null == isOpened || !isOpened){
                                isShare = true;
                                stringRedisTemplate.opsForSet().add("contentAction",contentAction.getNewsId() + parentCustomerId + contentAction.getCustomerId());
                            }
//                            if (isExit == 0) {
//                                isShare = true;
//                                syncContentDao.addContentActionFromMq(contentActionTmp);
//                            }
                        }
                    }
                }


                List<Map<String, Object>> scoreActiveList = scoreActDao.getScoreActAllList(orgId);
                for (Map<String, Object> map : scoreActiveList) {
                    String scoreType;
                    if ("1".equals(map.get("type").toString())) {
                        //积分
                        scoreType = "integral";
                    } else {
                        //成长值
                        scoreType = "growth";
                    }
                    switch (map.get("activeType").toString()) {
                        case "share":
                            if (contentAction.getUserOperate() == 0 && isShare) {
                               stringRedisTemplate.opsForValue().increment(ARTICLE_BEHAVIOR + orgId + "_share_" + scoreType + ":" + parentCustomerId, 1);
                            }
                            break;
                        case "givestar":
                            if (isExit == 0 && contentAction.getUserOperate() == 6) {
                                stringRedisTemplate.opsForValue().increment(ARTICLE_BEHAVIOR + orgId + "_givestar_" + scoreType + ":" + contentAction.getCustomerId(), 1);
                            }
                            break;
                        case "comment":
                            if (isExit == 0 && contentAction.getUserOperate() == 5) {
                                stringRedisTemplate.opsForValue().increment(ARTICLE_BEHAVIOR + orgId + "_comment_" + scoreType + ":" + contentAction.getCustomerId(), 1);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            syncContentDao.addContentActionFromMq(contentAction);

            // 阅读次数
            if (contentAction.getUserOperate() != 1) {
                // 不是阅读
                return;
            }

            // 判断机器人是否开启
            String conf = sysConfig.getSysConfByName(contentAction.getOrganizationNum(), MARKET_ROBOT_SWITCH);
            if ("0".equals(conf)) {
                return;
            }

            // 判断该文章是否为机器人在24小时内发给该用户的
            params.put("newsId", contentAction.getNewsId());
            Integer withinOneDay = robotSurveyService.judgeArticleSendWithinOneDay(params);
            if (withinOneDay == null || withinOneDay == 0) {
                return;
            }

            // 判断是否为第一次读
//        Integer integer = syncContentDao.judgeArticleIfRead(token, openid, contentAction.getNewsId());
            Map<String, Object> map = new HashMap<>();
            map.put("customerId", customerId);
            map.put("objectId", contentAction.getNewsId());
            map.put("actionType", 1);
            map.put("orgId", contentAction.getOrganizationNum());
            Integer integer = robotSurveyService.judgeFirstTimeByCidOidAndType(map);
            if (integer != 0) {
                // 不是第一次读
                return;
            }

            // 判断关注状态
            if (subscribe.equals(SUBSCRIBE_DEFAULT)) {
//            // 如果subscribe没有被修改，调矩阵查看用户关注状态
//            String result;
//            try {
//                result = httpService.doPost(systemProperties.getWxpushurl(), JSON.toJSONString(params));
//            } catch (Exception e) {
//                LOGGER.error("矩阵调用异常");
//                return;
//            }
//            WxUserInfoDto wxUserInfoDto = JSON.parseObject(result, WxUserInfoDto.class);
//            // 更新用户关注状态
//            subscribe = wxUserInfoDto.getData().getSubscribe();
                subscribe = customerDao.getCustomerSubscribeByCustomerId(customerId);
            }

            // 若关注，则阅读次数+1
            if (subscribe == 1) {
                // 获取文章标签
                String labelIds = syncContentDao.getLabelIdsByArticleId(contentAction.getNewsId());
                if (!StringUtils.isEmpty(labelIds)) {
                    // 给标签加阅读次数
                    String[] split = labelIds.split(",");
                    syncContentDao.addReadTimesByLabelIds(split);
                }
                // 给文章加阅读次数
                syncContentDao.addReadTimesByArticleId(contentAction.getNewsId());
                // 给data表加记录
                robotSurveyService.addToDealData(map);
            }
        } catch (Exception e) {
            LOGGER.error("mq数据错误");
            return;
        }


    }

}
